package com.tianqu.tms.www.car.controller;

import java.util.ArrayList;
import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.util.car.CarInformationApi;
import com.tianqu.tms.core.util.car.IdentifyModelByVinBean;
import com.tianqu.tms.dao.MemberDao;
import com.tianqu.tms.dao.TmsDao;
import com.tianqu.tms.dto.MarketCarInfoDto;
import com.tianqu.tms.dto.MemberDto;
import com.tianqu.tms.dto.TmsCarmodelVinDto;
import com.tianqu.tms.dto.TroubleCarInfoDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.CarModelInfo;
import com.tianqu.tms.entity.CarStyle;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.CommercialVehicle;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.TmsFragileStickerHistory;
import com.tianqu.tms.entity.VehicleBrand;
import com.tianqu.tms.entity.Vendor;
import com.tianqu.tms.www.car.viewhelper.CarCreationInputViewHelper;

/**
 * 库存查询-新增入库
 * @author mufeiyu
 *
 */
public class CarCreationEasyInputController extends TmsController {
	private Logger logger = Logger.getLogger(CarCreationEasyInputController.class);
	CarCreationInputViewHelper carCreationInputViewHelper = new CarCreationInputViewHelper();

	@SuppressWarnings("unchecked")
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			Car carInfo = Car.getInstance();
			Member member = Member.getInstance();
			TmsFragileStickerHistory tmsFragileStickerHistory = TmsFragileStickerHistory.getInstance();
			Codes code = Codes.getInstance();
			String vin = (String)uc.getParameter("vin");
			String realNamePy = (String)uc.getParameter("memberName");
			String name = "";
			String isAutoPayForRegister = Registry.getConfigFromDb(TmsConstants.ISAUTOPAYFORREGISTER);
			// 对车架号是否已经使用进行check
			String memberId = carInfo.vinCheck(vin);
			
			carCreationInputViewHelper.setMemberName(realNamePy);
			carCreationInputViewHelper.setMemberId((String)uc.getParameter("memberId"));
			uc.setAttribute(TmsConstants.VIEWHELP, carCreationInputViewHelper);
			
			if (!StringUtil.isNullOrBlank(memberId)){
					MemberDao mDao = (MemberDao) TmsDao.getInstance(TmsDao.TMS_MEMBER);
					MemberDto memberDto = mDao.findMemberInfoByMemId(memberId);
					uc.setAttribute("vinCheckError","err");
					uc.setAttribute("shortName", memberDto.getShortName());
			}
			
			if (StringUtil.isNotBlank(realNamePy) && realNamePy.indexOf("[") > 0 && realNamePy.indexOf("]") > 0) {
				name = realNamePy.substring(realNamePy.indexOf("[")+1,realNamePy.indexOf("]"));
			} else {
				name = realNamePy;
			}
			
			// 对商户名称是否存在进行check
			List<Member> realNamePyList = member.findMemberNameList(name,1);
			
			// 如果输入的商户存在，那么进行允许库存登记数量是否超数check
			if (null != realNamePyList && realNamePyList.size() > 0) {
				
				//通过所选商户ID到商户会员信息数据表（tms_member）中，查询对应的允许登记数量（annualTransactionVolume）
				int annualTransactionVolume = member.findAnnualTransactionVolume((String)uc.getParameter("memberId"));

				//再到库存车辆信息表（tms_market_car_info）中，获取商户会员ID为当前选择商户ID 并且 车辆库存状态为“1：已入库；2：已出库；6：登记”的数据总数
				int alreadyTransactionVolume = carInfo.getAlreadyTransactionVolumeByMemberId(memberId);
				
				//如果所得到数据总数大于或者等于允许库存登记数量，那么停止当前操作，页面提示“【U8004】当前商户的允许登记数量已经用完，无法进行保存。”

				if (alreadyTransactionVolume >= annualTransactionVolume) {
					uc.setAttribute("vinCheckError","err1");
				}
			} else {
				uc.setAttribute("vinCheckError","err2");
			}
			
			
			if (StringUtil.isNullOrBlank(memberId)){

				carCreationInputViewHelper.setVin(vin);
				// 车辆问题信息
				TroubleCarInfoDto troubleCarInfo = carInfo.getTroubleCarInfobyVin(vin);
				if (null != troubleCarInfo) {
					carCreationInputViewHelper.setTroubleId(troubleCarInfo.getId());
					carCreationInputViewHelper.setTroubleType(troubleCarInfo.getTroubleType());
					carCreationInputViewHelper.setTroubleTypeName(code.getItemValueByItemIdAndItemCode(Codes.TROUBLE_TYPE, troubleCarInfo.getTroubleType()));
					carCreationInputViewHelper.setTroubleRemark(troubleCarInfo.getRemark());
					carCreationInputViewHelper.setTroubleInsertTime(troubleCarInfo.getInsertTime());
				}
				
				// 车辆基本信息
				List<MarketCarInfoDto> carList = new ArrayList<MarketCarInfoDto>();
				carList = carInfo.findCarListIsCancel(vin, 1);
			
				if(carList.size() > 0){
					carCreationInputViewHelper.setColorList(code
							.getCodeslistByItemId(Codes.VEHICLE_COLOR));// 车辆颜色
	
					int isMatch = carList.get(0).getIsMatch();
					carCreationInputViewHelper.setIsMatch(isMatch);
					
					if(isMatch == 2)
					{
						carCreationInputViewHelper.setCarName(carList.get(0).getCarName());
						carCreationInputViewHelper.setBrandId(carList.get(0).getBrandId());
						carCreationInputViewHelper.setCarStyleId(carList.get(0).getCarStyleId());
						carCreationInputViewHelper.setVendorId(carList.get(0).getVendorId());
						
						CommercialVehicle commercialVehicle = CommercialVehicle.getInstance();
						// 车辆品牌
						Vendor vendor = Vendor.getInstance();
						if(!StringUtil.isNullOrBlank(carCreationInputViewHelper.getVendorId())){
							if("V".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
								carCreationInputViewHelper.setFromType(2);
								carCreationInputViewHelper.setVendorList(commercialVehicle.findAllVendorInfo());
							}else if("S".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
								carCreationInputViewHelper.setFromType(1);
								carCreationInputViewHelper.setVendorList(vendor.findAllVendorInfo());
							}
						}
						
					}
					else {
						CarModelInfo modelInfo = CarModelInfo.getInstance();
						TmsCarmodelVinDto carmodelVin = modelInfo.carmodelVinGet(null,vin);
						if(carmodelVin == null || StringUtil.isNullOrBlank(carmodelVin.getModelId())){
							IdentifyModelByVinBean identifyModelByVinBean = CarInformationApi.getIdentifyModelByVin(vin);
							if (!StringUtil.isNullOrBlank(identifyModelByVinBean.getModelId())){
								
								CarStyle carStyle = CarStyle.getInstance();
								carStyle = carStyle.findCarStyleInfo(identifyModelByVinBean.getModelId());
								if(!StringUtil.isNullOrBlank(carStyle.getCarStyleId())){
									carCreationInputViewHelper.setIsMatch(2);
									carCreationInputViewHelper.setCarName(carStyle.getCarStyleName());
									carCreationInputViewHelper.setCarStyleId(carStyle.getCarStyleId());
									carCreationInputViewHelper.setBrandId(carStyle.getBrandId());
									carCreationInputViewHelper.setVendorId(carStyle.getVendorId());
									
									CommercialVehicle commercialVehicle = CommercialVehicle.getInstance();
									// 车辆品牌
									Vendor vendor = Vendor.getInstance();
									if(!StringUtil.isNullOrBlank(carCreationInputViewHelper.getVendorId())){
										if("V".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
											carCreationInputViewHelper.setFromType(2);
											carCreationInputViewHelper.setVendorList(commercialVehicle.findAllVendorInfo());
										}else if("S".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
											carCreationInputViewHelper.setFromType(1);
											carCreationInputViewHelper.setVendorList(vendor.findAllVendorInfo());
										}
									}
								}else {
									if(!StringUtil.isNullOrBlank(carList.get(0).getCarName())){
										carCreationInputViewHelper.setCarName(carList.get(0).getCarName());
										carCreationInputViewHelper.setBrandId(carList.get(0).getBrandId());
										carCreationInputViewHelper.setCarStyleId(carList.get(0).getCarStyleId());
										carCreationInputViewHelper.setVendorId(carList.get(0).getVendorId());
										
										CommercialVehicle commercialVehicle = CommercialVehicle.getInstance();
										// 车辆品牌
										Vendor vendor = Vendor.getInstance();
										if(!StringUtil.isNullOrBlank(carCreationInputViewHelper.getVendorId())){
											if("V".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
												carCreationInputViewHelper.setFromType(2);
												carCreationInputViewHelper.setVendorList(commercialVehicle.findAllVendorInfo());
											}else if("S".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
												carCreationInputViewHelper.setFromType(1);
												carCreationInputViewHelper.setVendorList(vendor.findAllVendorInfo());
											}
										}
									}
								}
							}
							else
							{
								if(!StringUtil.isNullOrBlank(carList.get(0).getCarName())){
									carCreationInputViewHelper.setCarName(carList.get(0).getCarName());
									carCreationInputViewHelper.setBrandId(carList.get(0).getBrandId());
									carCreationInputViewHelper.setCarStyleId(carList.get(0).getCarStyleId());
									carCreationInputViewHelper.setVendorId(carList.get(0).getVendorId());
									
									CommercialVehicle commercialVehicle = CommercialVehicle.getInstance();
									// 车辆品牌
									Vendor vendor = Vendor.getInstance();
									if(!StringUtil.isNullOrBlank(carCreationInputViewHelper.getVendorId())){
										if("V".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
											carCreationInputViewHelper.setFromType(2);
											carCreationInputViewHelper.setVendorList(commercialVehicle.findAllVendorInfo());
										}else if("S".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
											carCreationInputViewHelper.setFromType(1);
											carCreationInputViewHelper.setVendorList(vendor.findAllVendorInfo());
										}
									}
								}
							}
						}else{
							CarStyle carStyle = CarStyle.getInstance();
							VehicleBrand vehicleBrand = VehicleBrand.getInstance();
							String styleNmae = carStyle.getCarStyleRNameById(carmodelVin.getModelId());
							String brandId = carStyle.getBrandIDByCarStyleID(carmodelVin.getModelId());
							String vendorId = vehicleBrand.getVendorIdByBrandId(brandId);
							carCreationInputViewHelper.setIsMatch(2);
							carCreationInputViewHelper.setCarName(styleNmae);
							carCreationInputViewHelper.setCarStyleId(carmodelVin.getModelId());
							carCreationInputViewHelper.setBrandId(brandId);
							carCreationInputViewHelper.setVendorId(vendorId);
							
							CommercialVehicle commercialVehicle = CommercialVehicle.getInstance();
							// 车辆品牌
							Vendor vendor = Vendor.getInstance();
							if(!StringUtil.isNullOrBlank(carCreationInputViewHelper.getVendorId())){
								if("V".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
									carCreationInputViewHelper.setFromType(2);
									carCreationInputViewHelper.setVendorList(commercialVehicle.findAllVendorInfo());
								}else if("S".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
									carCreationInputViewHelper.setFromType(1);
									carCreationInputViewHelper.setVendorList(vendor.findAllVendorInfo());
								}
							}
						}
					}
					
					member.findMemberInfoByMemId(String.valueOf(carList.get(0).getMemberId()));
					carCreationInputViewHelper.setFragileStickerFreePort(member.getFragileStickerFreePort());
					int annualTransactionVolume = member.getAnnualTransactionVolume();
					carCreationInputViewHelper.setAnnualTransactionVolume(String.valueOf(annualTransactionVolume));					
					carCreationInputViewHelper.setAlreadyTransactionVolume(carInfo.getAlreadyTransactionVolumeByMemberId(String.valueOf(carList.get(0).getMemberId())));

					int fragileSticker = tmsFragileStickerHistory.getFragileStickerByMemberId(String.valueOf(carList.get(0).getMemberId()));
					carCreationInputViewHelper.setFragileSticker(fragileSticker); 
					carCreationInputViewHelper.setRegisterStatus(3);					
					carCreationInputViewHelper.setRegDate(carList.get(0).getRegDate());
					carCreationInputViewHelper.setYearCarefulPeriod(carList.get(0).getYearCarefulPeriod());
					carCreationInputViewHelper.setJqx(carList.get(0).getJqx());
					carCreationInputViewHelper.setSendCardDate(carList.get(0).getSendCardDate());
					carCreationInputViewHelper.setColor(StringUtil.getString(carList.get(0).getColor()));
					carCreationInputViewHelper.setCarOwner(carList.get(0).getCarOwner());
					carCreationInputViewHelper.setOwnerPhone(carList.get(0).getOwnerPhone());
					carCreationInputViewHelper.setMileage(String.valueOf(carList.get(0).getMileage()));
					carCreationInputViewHelper.setPrice(String.valueOf(carList.get(0).getPrice()));
					carCreationInputViewHelper.setImg1(carList.get(0).getPhoto_1());
					carCreationInputViewHelper.setImg2(carList.get(0).getPhoto_2());
					carCreationInputViewHelper.setImg3(carList.get(0).getPhoto_3());
					carCreationInputViewHelper.setImg4(carList.get(0).getPhoto_4());
					carCreationInputViewHelper.setImg5(carList.get(0).getPhoto_5());
					carCreationInputViewHelper.setImg6(carList.get(0).getPhoto_6());
					carCreationInputViewHelper.setImg7(carList.get(0).getPhoto_7());
					carCreationInputViewHelper.setImg8(carList.get(0).getPhoto_8());
					carCreationInputViewHelper.setLicensePlate(carList.get(0).getLicensePlate());
					carCreationInputViewHelper.setTempLicensePlate(carList.get(0).getTempLicensePlate());
					//carCreationInputViewHelper.setMemberId(StringUtil.getString(carList.get(0).getMemberId()));
					//carCreationInputViewHelper.setMemberName(carList.get(0).getMemberName());
					carCreationInputViewHelper.setIsAutoPayForRegister(Integer.valueOf(isAutoPayForRegister));
					carCreationInputViewHelper.setSerial(carList.get(0).getSerial());
				}
				else {
					
					carCreationInputViewHelper.setIsMatch(1);
					
					CarModelInfo modelInfo = CarModelInfo.getInstance();
					TmsCarmodelVinDto carmodelVin = modelInfo.carmodelVinGet(null,vin);
					if(carmodelVin == null || StringUtil.isNullOrBlank(carmodelVin.getModelId())){
						IdentifyModelByVinBean identifyModelByVinBean = CarInformationApi.getIdentifyModelByVin(vin);
						if (!StringUtil.isNullOrBlank(identifyModelByVinBean.getModelId())){
							
							CarStyle carStyle = CarStyle.getInstance();
							carStyle = carStyle.findCarStyleInfo(identifyModelByVinBean.getModelId());
							if(!StringUtil.isNullOrBlank(carStyle.getCarStyleId())){
								carCreationInputViewHelper.setIsMatch(2);
								carCreationInputViewHelper.setCarName(carStyle.getCarStyleName());
								carCreationInputViewHelper.setCarStyleId(carStyle.getCarStyleId());
								carCreationInputViewHelper.setBrandId(carStyle.getBrandId());
								carCreationInputViewHelper.setVendorId(carStyle.getVendorId());
								
								CommercialVehicle commercialVehicle = CommercialVehicle.getInstance();
								// 车辆品牌
								Vendor vendor = Vendor.getInstance();
								if(!StringUtil.isNullOrBlank(carCreationInputViewHelper.getVendorId())){
									if("V".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
										carCreationInputViewHelper.setFromType(2);
										carCreationInputViewHelper.setVendorList(commercialVehicle.findAllVendorInfo());
									}else if("S".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
										carCreationInputViewHelper.setFromType(1);
										carCreationInputViewHelper.setVendorList(vendor.findAllVendorInfo());
									}
								}
							}
						}
					}else{
						CarStyle carStyle = CarStyle.getInstance();
						VehicleBrand vehicleBrand = VehicleBrand.getInstance();
						String styleNmae = carStyle.getCarStyleRNameById(carmodelVin.getModelId());
						String brandId = carStyle.getBrandIDByCarStyleID(carmodelVin.getModelId());
						String vendorId = vehicleBrand.getVendorIdByBrandId(brandId);
						carCreationInputViewHelper.setIsMatch(2);
						carCreationInputViewHelper.setCarName(styleNmae);
						carCreationInputViewHelper.setCarStyleId(carmodelVin.getModelId());
						carCreationInputViewHelper.setBrandId(brandId);
						carCreationInputViewHelper.setVendorId(vendorId);
						carCreationInputViewHelper.setCarNameVisibleFlag(1);
						
						CommercialVehicle commercialVehicle = CommercialVehicle.getInstance();
						// 车辆品牌
						Vendor vendor = Vendor.getInstance();
						if(!StringUtil.isNullOrBlank(carCreationInputViewHelper.getVendorId())){
							if("V".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
								carCreationInputViewHelper.setFromType(2);
								carCreationInputViewHelper.setVendorList(commercialVehicle.findAllVendorInfo());
							}else if("S".equals(carCreationInputViewHelper.getVendorId().substring(0,1))){
								carCreationInputViewHelper.setFromType(1);
								carCreationInputViewHelper.setVendorList(vendor.findAllVendorInfo());
							}
						}
					}
					carCreationInputViewHelper.setModelCode("");
					carCreationInputViewHelper.setVendorCode("");
					
					carCreationInputViewHelper.setCardTypeList(code.getCodeslistByItemId(Codes.PLATE_TYPE));// 号牌种类list
					carCreationInputViewHelper.setMemberList(member.findAllMemInfo(1));// 会员类型  
					String lPlate = Registry.getConfig(TmsConstants.TMS_DEFLICENSEPLATE_KEY);//车牌前两位
					carCreationInputViewHelper.setLicensePlate(lPlate);
					carCreationInputViewHelper.setAttestStatus(1);
					carCreationInputViewHelper.setColorList(code.getCodeslistByItemId(Codes.VEHICLE_COLOR));// 车辆颜色
					carCreationInputViewHelper.setIsAutoPayForRegister(Integer.valueOf(isAutoPayForRegister));
				}
			}
			
			uc.setAttribute(TmsConstants.VIEWHELP, carCreationInputViewHelper);
			logger.debug(this.getClass().getName() + "#execute was completed.");
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
	}
}
